package com.pb.camera.jph.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import com.pb.camera.R;
import com.pb.camera.application.App;
import com.pb.camera.bean.AllRoom;
import com.pb.camera.bean.DeviceMode;
import com.pb.camera.bean.Room;
import com.pb.camera.selectroom.spinner.SpinerPopWindow;
import com.pb.camera.selectroom.spinner.AbstractSpinerAdapter.IOnItemSelectListener;
import com.pb.camera.utils.Assert;
import com.pb.camera.utils.TaskHelper;
import com.pb.camera.view.MySeekBar;
import com.pb.camera.view.ProgressDialog;
import com.pb.camera.work.dr_peng.ChannleWorkInterface;
import com.pb.camera.work.dr_peng.DrPengChannleWork;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ActionBar.LayoutParams;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class SettingCameraRoomActivity extends Activity implements OnClickListener,IOnItemSelectListener{
	private static final int SHOW_PROGRESS = 0;
	private static final int SHOW_TOAST = 1;
	private ImageButton ib_back_add,bt_dropdown;
	private Button mBtn_name_success;
	private TextView tv_camera_room_select,tv_add_new_room;
	private SpinerPopWindow mSpinerPopWindow;
	private List<Room> mAllRoom;
	private int roomPosition = 0;
	private EditText et_roomname;
	private ProgressDialog mProgressDialog;
	private List<String> mRoomNames;
	private DeviceMode mDevice;
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == SHOW_PROGRESS)
				mProgressDialog.show();
			if (msg.what == SHOW_TOAST)
				Toast.makeText(SettingCameraRoomActivity.this,(String)msg.obj,Toast.LENGTH_SHORT).show();
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting_camera_room);
		initView();
		initData();
	}

	private void initView() {
		ib_back_add = (ImageButton) findViewById(R.id.ib_back_add);
		bt_dropdown = (ImageButton) findViewById(R.id.bt_dropdown);
		tv_camera_room_select = (TextView) findViewById(R.id.tv_camera_room_select);
		tv_add_new_room = (TextView) findViewById(R.id.tv_add_new_room);
		mBtn_name_success = (Button) findViewById(R.id.btn_name_success);
		mProgressDialog = new ProgressDialog(this,true);
	}

	private void initData() {
		ib_back_add.setOnClickListener(this);
		tv_camera_room_select.setOnClickListener(this);
		bt_dropdown.setOnClickListener(this);
		tv_add_new_room.setOnClickListener(this);
		mBtn_name_success.setOnClickListener(this);
		mRoomNames = new ArrayList<>();
		Intent intent = getIntent();
		mDevice = (DeviceMode)intent.getSerializableExtra("device");
		//查找所有房间,封装集合并且选择
		if (App.getInstance().getAllRoom() == null){
			mProgressDialog.show();
			DrPengChannleWork.getAllRoom(new ChannleWorkInterface<AllRoom>() {
				@Override
				public  AllRoom onSuccess(AllRoom allRoom) {
					Assert.notNull(allRoom);
					App.getInstance().setAllRoom(allRoom);
					mAllRoom = allRoom.getData();
					getStringFromAllRoom();
					mSpinerPopWindow.refreshData(mRoomNames, 0);
					mProgressDialog.dismiss();
					return allRoom;
				}

				@Override
				public void onFailed(String msg) {
					mProgressDialog.dismiss();
					if (msg != null)
						msg = getString(R.string.query_room_failed)+":"+msg;
					Message message = new Message();
					message.what = SHOW_TOAST;
					message.obj = msg;
					handler.sendMessage(message);
				}
			});
		}else {
			mAllRoom = App.getInstance().getAllRoom().getData();
			getStringFromAllRoom();
		}
		setupViews();

	}

	private void getStringFromAllRoom() {
		for (Room room : mAllRoom){
			mRoomNames.add(room.getName());
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ib_back_add:
			finish();
			break;
		case R.id.bt_dropdown:
		case R.id.tv_camera_room_select:
			showSpinWindow();
			break;
		case R.id.tv_add_new_room:
			showDailogAddRoom();
			break;
		case R.id.btn_name_success:
			if(tv_camera_room_select.getText() != null){
				mDevice.setGname(tv_camera_room_select.getText().toString());
				Intent intentC = new Intent(this, SettingCameraNetActivity.class);
				intentC.putExtra("device",mDevice);
				startActivity(intentC);
			}
			break;
		}
	}
	
	private void setupViews(){
		mSpinerPopWindow = new SpinerPopWindow(getApplicationContext());
		mSpinerPopWindow.refreshData(mRoomNames, 0);
		mSpinerPopWindow.setItemListener(this);
    }
	
	private void showSpinWindow(){
		Log.e("", "showSpinWindow");
		mSpinerPopWindow.setWidth(tv_camera_room_select.getWidth());
		mSpinerPopWindow.showAsDropDown(tv_camera_room_select);
	}
	
	private String stringFilter(String str)throws PatternSyntaxException{ 
		  String regEx = "[/\\:*?<>|\"\n\t]"; //要过滤掉的字符
		  Pattern p = Pattern.compile(regEx); 
		  Matcher m = p.matcher(str); 
		  return m.replaceAll("").trim(); 
	}

	@Override
	public void onItemClick(int pos) {
		setHero(pos);
		roomPosition = pos;
		mBtn_name_success.setEnabled(true);
	}
	
	private void setHero(int pos){
		if (pos >= 0 && pos <= mRoomNames.size()){
			String value = mRoomNames.get(pos);
			if (mDevice!= null){
				tv_camera_room_select.setText(value);
				mDevice.setDevgroupId(mAllRoom.get(pos).getGids() + "");
				mDevice.setGname(value);
			}
		}
	}
	
	protected void showDailogAddRoom() {
		Builder builder = new Builder(this);
		//获取对话框对象
		final AlertDialog dialog = builder.create();  
		builder.setCancelable(false);
		//修改对话框的样式(布局结构)
		View view = View.inflate(this,R.layout.dialog_add_room, null);
		TextView tv_delete = (TextView) view.findViewById(R.id.tv_delete);
		TextView bt_submit = (TextView) view.findViewById(R.id.bt_submit);
		TextView bt_cancel = (TextView) view.findViewById(R.id.bt_cancel);
		et_roomname = (EditText) view.findViewById(R.id.et_roomname);
		
		//控制输入的字符个数和输入的符号
		final int maxLength = 4;
		et_roomname.addTextChangedListener(new TextWatcher() {
			private int cou = 0;
			int selectionEnd = 0;

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				cou = before + count;
				String editable = et_roomname.getText().toString();
				String str = stringFilter(editable); //过滤特殊字符
				if (!editable.equals(str)) {
					et_roomname.setText(str);
				}
				et_roomname.setSelection(et_roomname.length());
				cou = et_roomname.length();
				if (str.length() == 0)
					mBtn_name_success.setEnabled(false);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
										  int after) {}

			@Override
			public void afterTextChanged(Editable s) {
				if (cou > maxLength) {
					selectionEnd = et_roomname.getSelectionEnd();
					s.delete(maxLength, selectionEnd);
				}
			}
		});

		tv_delete.setText("添加房间");
		tv_delete.setTextColor(Color.BLACK);  
		bt_submit.setTextColor(Color.BLACK);
		bt_cancel.setTextColor(Color.BLACK);
		dialog.setView(new EditText(this));
		dialog.show();
		WindowManager m = dialog.getWindow().getWindowManager();
	    Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
	    WindowManager.LayoutParams p = dialog.getWindow().getAttributes(); // 获取对话框当前的参数值
		p.height = LayoutParams.WRAP_CONTENT;
		p.width = LayoutParams.WRAP_CONTENT;
	    dialog.getWindow().setAttributes(p);
		dialog.setContentView(view);
		bt_submit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final String roomName = et_roomname.getText().toString().trim();
				if(TextUtils.isEmpty(roomName)){
					Toast.makeText(SettingCameraRoomActivity.this, "房间名称不能为空", Toast.LENGTH_SHORT).show();
				}else{
					dialog.dismiss();
					//添加新房间
					tv_camera_room_select.setText(roomName);
					DrPengChannleWork.creatGroup(roomName, new ChannleWorkInterface<String>() {
						@Override
						public String onSuccess(String groupId) {
							TaskHelper.exec(new TaskHelper.UITask() {
								@Override
								public void callback(Exception e) {
									mBtn_name_success.setEnabled(true);
								}
							});
							mDevice.setDevgroupId(groupId);
							return  null;
						}
						@Override
						public void onFailed(String o) {
							if (o != null)
								o = getString(R.string.creat_room_failed)+":"+o;
							Message msg = new Message();
							msg.what = SHOW_TOAST;
							msg.obj = o;
							handler.sendMessage(msg);
						}
					});
				}
			}
		});
		bt_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
	}

}
